package com.huo.util;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.codec.binary.Hex;

public class DESUtil {

	private static final String sKey = "20190417";

	public static SecretKey makeSecretKey() {
		SecretKey key2 = null;
		try {
			byte[] key = sKey.getBytes();// 生成key
			// key转换成密钥
			DESKeySpec desKeySpec = new DESKeySpec(key);
			SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
			key2 = factory.generateSecret(desKeySpec); // 转换后的密钥
			return key2;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return key2;
	}

	public static String DESEnc(String src) {
		try {
			Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); // 算法类型/工作方式/填充方式
			cipher.init(Cipher.ENCRYPT_MODE, makeSecretKey()); // 指定为加密模式
			byte[] result = cipher.doFinal(src.getBytes());
			return Hex.encodeHexString(result).toString();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	public static String DESDec(String encStr) {
		try {
			Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); // 算法类型/工作方式/填充方式
			cipher.init(Cipher.DECRYPT_MODE, makeSecretKey()); // 相同密钥，指定为解密模式
			byte[] enc = Hex.decodeHex(encStr.toCharArray());
			byte[] result = cipher.doFinal(enc); // 根据加密内容解密
			return new String(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	public static void main(String[] args) {
		String enc = DESEnc("1111111111");
		System.out.println(enc + " " + enc.length());
		String re = DESDec(enc);
		System.out.println(re);
	}
}
